<template>
  <div class="question-bank-container">
    <el-card shadow="never" class="header-card">
      <div class="page-header">
        <div class="header-content">
          <el-icon class="header-icon" :size="28"><Collection /></el-icon>
          <div class="header-text">
            <h2>题库管理</h2>
            <p>试题资源库管理</p>
          </div>
        </div>
        <div class="header-actions">
          <el-button type="primary" @click="showDialog = true">
            <el-icon><Plus /></el-icon>
            添加试题
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 题目统计 -->
    <div class="stats-row">
      <el-card shadow="hover" class="stat-card">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#409EFF"><Document /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.total }}</div>
            <div class="stat-label">全部题目</div>
          </div>
        </div>
      </el-card>
      <el-card shadow="hover" class="stat-card">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#67C23A"><CircleCheck /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.single }}</div>
            <div class="stat-label">单选题</div>
          </div>
        </div>
      </el-card>
      <el-card shadow="hover" class="stat-card">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#E6A23C"><Menu /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.multiple }}</div>
            <div class="stat-label">多选题</div>
          </div>
        </div>
      </el-card>
      <el-card shadow="hover" class="stat-card">
        <div class="stat-content">
          <el-icon class="stat-icon" :size="40" color="#F56C6C"><Edit /></el-icon>
          <div class="stat-info">
            <div class="stat-value">{{ stats.essay }}</div>
            <div class="stat-label">问答题</div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 筛选区域 -->
    <el-card shadow="never" class="filter-card">
      <el-form :inline="true" :model="searchForm">
        <el-form-item label="题目内容">
          <el-input v-model="searchForm.content" placeholder="请输入关键词" clearable style="width: 200px" />
        </el-form-item>
        <el-form-item label="题目类型">
          <el-select v-model="searchForm.type" placeholder="请选择" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="单选题" value="single" />
            <el-option label="多选题" value="multiple" />
            <el-option label="判断题" value="judge" />
            <el-option label="问答题" value="essay" />
          </el-select>
        </el-form-item>
        <el-form-item label="难度">
          <el-select v-model="searchForm.difficulty" placeholder="请选择" clearable style="width: 150px">
            <el-option label="全部" value="" />
            <el-option label="简单" value="简单" />
            <el-option label="中等" value="中等" />
            <el-option label="困难" value="困难" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            查询
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 题目列表 -->
    <el-card shadow="never">
      <el-table :data="tableData" stripe>
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="content" label="题目内容" min-width="300" show-overflow-tooltip />
        <el-table-column prop="type" label="题型" width="100">
          <template #default="{ row }">
            <el-tag size="small">{{ getQuestionTypeName(row.type) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="difficulty" label="难度" width="100">
          <template #default="{ row }">
            <el-tag :type="getDifficultyType(row.difficulty)" size="small">
              {{ row.difficulty }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="默认分值" width="100" />
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="useCount" label="使用次数" width="100" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button link type="success" @click="handlePreview(row)">
              <el-icon><View /></el-icon>
              预览
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        style="margin-top: 20px; justify-content: flex-end;"
      />
    </el-card>

    <!-- 新建/编辑题目对话框 -->
    <el-dialog
      v-model="showDialog"
      :title="dialogTitle"
      width="800px"
      destroy-on-close
    >
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="题目类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="single">单选题</el-radio>
            <el-radio label="multiple">多选题</el-radio>
            <el-radio label="judge">判断题</el-radio>
            <el-radio label="essay">问答题</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="题目内容" prop="content">
          <el-input v-model="form.content" type="textarea" :rows="4" placeholder="请输入题目内容" />
        </el-form-item>
        
        <!-- 选择题选项 -->
        <template v-if="form.type === 'single' || form.type === 'multiple'">
          <el-form-item
            v-for="(option, index) in form.options"
            :key="index"
            :label="'选项' + String.fromCharCode(65 + index)"
          >
            <el-input v-model="option.content" placeholder="请输入选项内容">
              <template #append>
                <el-checkbox v-model="option.isAnswer">正确答案</el-checkbox>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button @click="addOption" v-if="form.options.length < 6">
              <el-icon><Plus /></el-icon>
              添加选项
            </el-button>
            <el-button @click="removeOption" v-if="form.options.length > 2">
              <el-icon><Delete /></el-icon>
              删除选项
            </el-button>
          </el-form-item>
        </template>

        <!-- 判断题答案 -->
        <el-form-item v-if="form.type === 'judge'" label="正确答案" prop="judgeAnswer">
          <el-radio-group v-model="form.judgeAnswer">
            <el-radio :label="true">正确</el-radio>
            <el-radio :label="false">错误</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 问答题参考答案 -->
        <el-form-item v-if="form.type === 'essay'" label="参考答案" prop="essayAnswer">
          <el-input v-model="form.essayAnswer" type="textarea" :rows="4" placeholder="请输入参考答案" />
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="8">
            <el-form-item label="题目分类" prop="category">
              <el-input v-model="form.category" placeholder="如：Vue基础" />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="难度" prop="difficulty">
              <el-select v-model="form.difficulty" placeholder="请选择" style="width: 100%">
                <el-option label="简单" value="简单" />
                <el-option label="中等" value="中等" />
                <el-option label="困难" value="困难" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="默认分值" prop="score">
              <el-input-number v-model="form.score" :min="1" :max="100" style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="题目解析">
          <el-input v-model="form.explanation" type="textarea" :rows="3" placeholder="请输入题目解析（选填）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSave">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Collection, Plus, Search, Refresh, Document, Edit, Delete, View,
  CircleCheck, Menu
} from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  content: '',
  type: '',
  difficulty: ''
})

// 统计数据
const stats = reactive({
  total: 156,
  single: 80,
  multiple: 45,
  essay: 31
})

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 156
})

// 表格数据
const tableData = ref([
  {
    id: 1,
    content: 'Vue 3 的 Composition API 中，ref 和 reactive 的区别是什么？',
    type: 'single',
    difficulty: '中等',
    score: 5,
    category: 'Vue基础',
    useCount: 12
  },
  {
    id: 2,
    content: '以下哪些是 Vue 3 的新特性？',
    type: 'multiple',
    difficulty: '中等',
    score: 8,
    category: 'Vue基础',
    useCount: 10
  },
  {
    id: 3,
    content: 'Vue 3 完全向后兼容 Vue 2。',
    type: 'judge',
    difficulty: '简单',
    score: 3,
    category: 'Vue基础',
    useCount: 15
  },
  {
    id: 4,
    content: '请简述 Vue 3 的响应式原理。',
    type: 'essay',
    difficulty: '困难',
    score: 15,
    category: 'Vue进阶',
    useCount: 8
  }
])

// 对话框
const showDialog = ref(false)
const formRef = ref(null)
const currentRow = ref(null)
const currentExamQuestions = ref([])

const dialogTitle = computed(() => currentRow.value ? '编辑题目' : '添加题目')

// 表单
const form = reactive({
  type: 'single',
  content: '',
  options: [
    { content: '', isAnswer: false },
    { content: '', isAnswer: false }
  ],
  judgeAnswer: true,
  essayAnswer: '',
  category: '',
  difficulty: '中等',
  score: 5,
  explanation: ''
})

// 表单验证规则
const rules = {
  content: [{ required: true, message: '请输入题目内容', trigger: 'blur' }],
  category: [{ required: true, message: '请输入题目分类', trigger: 'blur' }]
}

// 方法
const handleSearch = () => {
  console.log('搜索', searchForm)
  ElMessage.success('查询成功')
}

const handleReset = () => {
  Object.assign(searchForm, {
    content: '',
    type: '',
    difficulty: ''
  })
}

const handleEdit = (row) => {
  currentRow.value = row
  Object.assign(form, {
    type: row.type,
    content: row.content,
    category: row.category,
    difficulty: row.difficulty,
    score: row.score
  })
  showDialog.value = true
}

const handlePreview = (row) => {
  ElMessageBox.alert(
    `题目：${row.content}\n类型：${getQuestionTypeName(row.type)}\n难度：${row.difficulty}\n分值：${row.score}分`,
    '题目预览',
    { confirmButtonText: '确定' }
  )
}

const handleDelete = (row) => {
  ElMessageBox.confirm('确定要删除该题目吗？', '提示', {
    type: 'warning'
  }).then(() => {
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
    }
    ElMessage.success('删除成功')
  }).catch(() => {})
}

const handleSave = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      ElMessage.success('保存成功')
      showDialog.value = false
    }
  })
}

const addOption = () => {
  form.options.push({ content: '', isAnswer: false })
}

const removeOption = () => {
  form.options.pop()
}

const getQuestionTypeName = (type) => {
  const map = {
    single: '单选题',
    multiple: '多选题',
    judge: '判断题',
    essay: '问答题'
  }
  return map[type] || type
}

const getDifficultyType = (difficulty) => {
  const map = {
    简单: 'success',
    中等: 'warning',
    困难: 'danger'
  }
  return map[difficulty] || ''
}
</script>

<style scoped>
.question-bank-container {
  padding: 20px;
}

.header-card {
  margin-bottom: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  color: #409EFF;
}

.header-text h2 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.header-text p {
  margin: 4px 0 0 0;
  font-size: 14px;
  color: #909399;
}

.stats-row {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 20px;
  margin-bottom: 20px;
}

.stat-card {
  cursor: pointer;
  transition: all 0.3s;
}

.stat-card:hover {
  transform: translateY(-4px);
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.filter-card {
  margin-bottom: 20px;
}
</style>

